package org.ttitfly.workflow.handler;

import java.lang.reflect.Method;

/**
 * 反射方法调用
 * 
 * @author 潘海春
 * @version 2009-9-24
 */
public class ReflectMethodInvoker {

	/**
	 * 调用的方法
	 */
	protected Method method;

	/**
	 * 对象
	 */
	protected Object target;

	/**
	 * 构造函数
	 * 
	 * @param target
	 * @param methodName
	 * @param argNames
	 */
	public ReflectMethodInvoker(Object target, String methodName, String... argNames) {
		if (target == null) {
			throw new IllegalArgumentException("argument target can not be null!");
		}
		this.target = target;
		Method[] methods = target.getClass().getMethods();
		int argLen = (argNames == null || argNames.length == 0) ? 0 : argNames.length;
		for (Method method : methods) {
			if (method.getName().equals(methodName) && method.getParameterTypes().length == argLen) {
				this.method = method;
				break;
			}
		}
		if (method == null) {
			throw new IllegalArgumentException("can not find method named：" + methodName + " and with the arguments!");
		}
	}

	/**
	 * 构造函数
	 * 
	 * @param method
	 * @param target
	 */
	public ReflectMethodInvoker(Method method, Object target) {
		if (method == null) {
			throw new IllegalArgumentException("argument method can not be null!");
		}
		if (target == null) {
			throw new IllegalArgumentException("component method can not be null!");
		}
		this.method = method;
		this.target = target;
	}

	/**
	 * 调用反射方法
	 * 
	 * @param args
	 * @return
	 * @throws Exception
	 */
	public Object invoke(Object... args) throws Exception {
		return method.invoke(target, args);
	}
}
